﻿//---------------------------------------------------------------
// <copyright company="CounterSoft Limited">
//     Copyright (c) CounterSoft Limited. All rights reserved.
// </copyright> 
//---------------------------------------------------------------
using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using CounterSoft.Gemini.WebServices;
using CounterSoft.Gemini.Commons;
using CounterSoft.Gemini.Commons.Entity;
using CounterSoft.Gemini.Logging;
using Greenshot.Helpers;
using Microsoft.Win32;

namespace Greenshot
{
    public partial class GeminiForm : Form
    {
        #region Variables

        private ServiceManager serviceManager;
        private string formCaption = "Greenshot Send to Gemini";
        private Bitmap screenCapture;
        private string filename = "";

        #endregion

        #region Lifecycle

        public GeminiForm()
        {
            InitializeComponent();
        }

        public GeminiForm(Bitmap screenCapture, string filename)
        {
            InitializeComponent();
            this.screenCapture = screenCapture;
            this.filename = filename;

            try
            {
                RegistryKey rk = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Greenshot Screen Capture\\SendTo\\Gemini");

                if (rk != null)
                {
                    txtURL.Text = rk.GetValue("Url", "http://server/gemini").ToString();
                    txtUsername.Text = rk.GetValue("Username", "manager").ToString();
                }
            }
            catch (Exception ex)
            {
                DiagnosticsManager.TraceException("Failure", ex);
            }

        }

        #endregion

        #region Events

        private void btnSend_Click(object sender, EventArgs e)
        {
            try
            {
                serviceManager = new ServiceManager(txtURL.Text, txtUsername.Text, txtPassword.Text, "", chkWinAuth.Checked);
                UserEN user;
                IssueEN issue;
                int issueId = 0;
                GeminiConfigurationEN config;

                user = serviceManager.UsersService.WhoAmI();
                config = serviceManager.AdminService.GetConfiguration();

                try
                {
                    issueId = Int32.Parse(txtIssueID.Text);
                }
                catch
                {
                }

                if (issueId == 0)
                {
                    MessageBox.Show("Invalid Issue ID.", formCaption, MessageBoxButtons.OK, MessageBoxIcon.Error);

                    return;
                }

                issue = serviceManager.IssuesService.GetIssue(issueId);

                if (issue.IssueID < 1)
                {
                    MessageBox.Show("No issue found.", formCaption, MessageBoxButtons.OK, MessageBoxIcon.Error);

                    return;
                }

                IssueCommentEN comment = new IssueCommentEN();
                comment.IssueID = issueId;
                comment.UserID = user.UserID;
                comment.Comment = txtComment.Text;
                comment.ProjectID = issue.ProjectID;

                FileEN file = new FileEN();

                MemoryStream ms = new MemoryStream();
                screenCapture.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
                Byte[] fileContent = ms.ToArray();

                file.IssueID = issueId;
                file.ContentLength = fileContent.Length;
                file.ContentType = GetContentType(filename);
                file.FileData = fileContent;
                file.ProjectID = issue.ProjectID;
                file.FileName = Path.GetFileName(filename);

                comment.Attachment = file;
                comment = serviceManager.IssuesService.CreateComment(issueId, comment);

                if (!config.FullGeminiURL.EndsWith("/")) config.FullGeminiURL += "/";

                string issueUrl = String.Format("{0}Default.aspx?p={1}&i={2}", config.FullGeminiURL, issue.ProjectID, issue.IssueID);

                GeminiSuccessForm success = new GeminiSuccessForm(issueUrl);
                success.ShowDialog();
                success.Close();

                try
                {
                    RegistryKey rk = Registry.CurrentUser.CreateSubKey("SOFTWARE\\Greenshot Screen Capture\\SendTo\\Gemini");

                    if (rk != null)
                    {
                        rk.SetValue("Url", txtURL.Text, RegistryValueKind.String);
                        rk.SetValue("Username", txtUsername.Text, RegistryValueKind.String);
                    }
                }
                catch (Exception ex)
                {
                    DiagnosticsManager.TraceException("Failure", ex);
                }

                this.Close();
            }
            catch (Exception ex)
            {
                string msg = String.Format("Error encountered. {0} {1} {2}", Environment.NewLine, Environment.NewLine, ex.Message);

                MessageBox.Show(msg, formCaption, MessageBoxButtons.OK, MessageBoxIcon.Error);

                DiagnosticsManager.TraceException("Failure", ex);

                return;
            }
        }

        private void GeminiForm_Load(object sender, EventArgs e)
        {
            if (txtUsername.Text.Length > 0)
            {
                txtIssueID.Focus();
            }
        }

        #endregion

        #region Helpers

        private static string GetContentType(string fileName)
        {
            fileName = fileName.Trim().ToUpper();

            if (fileName.EndsWith(".JPG"))
            {
                return "image/jpg";
            }
            else if (fileName.EndsWith(".GIF"))
            {
                return "image/gif";
            }
            else if (fileName.EndsWith(".PNG"))
            {
                return "image/png";
            }
            else if (fileName.EndsWith(".BMP"))
            {
                return "image/bmp";
            }
            else if (fileName.EndsWith(".TXT"))
            {
                return "text/plain";
            }
            else if (fileName.EndsWith(".DOC"))
            {
                return "application/msword";
            }
            else if (fileName.EndsWith(".XLS"))
            {
                return "application/vnd.ms-excel";
            }
            else if (fileName.EndsWith(".ZIP"))
            {
                return "application/x-zip-compressed";
            }
            else if (fileName.EndsWith(".EXE"))
            {
                return "application/octet-stream";
            }
            else
            {
                return "text/plain";
            }
        }

        private void chkWinAuth_CheckedChanged(object sender, EventArgs e)
        {
            txtUsername.Enabled = !chkWinAuth.Checked;
            txtPassword.Enabled = !chkWinAuth.Checked;

            if (txtUsername.Enabled)
            {
                txtUsername.Text = "";
            }
            else
            {
                txtUsername.Text = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
            }
        }

        #endregion
    }
}
